package cc.wangweiye.distributelock.perfect;

import cc.wangweiye.distributelock.DistributedLock;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.UUID;

public class Service2 {

    private static JedisPool pool = null;
    private RedisTool lock = new RedisTool();

    int n = 500;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        // 设置最大连接数
        config.setMaxTotal(500);
        // 设置最大空闲数
        config.setMaxIdle(8);
        // 设置最大等待时间
        config.setMaxWaitMillis(1000 * 100);
        // 在borrow一个jedis实例时，是否需要验证，若为true，则所有jedis实例均是可用的
        config.setTestOnBorrow(true);
        pool = new JedisPool(config, "127.0.0.1", 6379, 3000);
    }

    public void seckill() {
        Jedis jedis = pool.getResource();
        // 返回锁的value值，供释放锁时候进行判断
        String uuid = UUID.randomUUID().toString();

        while (true) {
            boolean locked = lock.tryGetDistributedLock(jedis, "resource", uuid, 500);

            if (locked) {
                System.out.println(Thread.currentThread().getName() + "获得了锁");
                System.out.println(--n);
                break;
            }
        }

        lock.releaseDistributedLock(jedis, "resource", uuid);
    }
}